package com.example.agriapp.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.agriapp.data.AgriDatabaseHelper;
import com.example.agriapp.model.bean.User;
import com.example.agriapp.R;
import com.example.agriapp.util.SharedPrefUtils;


public class LoginActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView btnRegister;
    private AgriDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_nav_icon_selected));

        dbHelper = new AgriDatabaseHelper(this);

        etUsername = findViewById(R.id.et_name);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);

        btnLogin.setOnClickListener(v -> loginUser());
        btnRegister.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void loginUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if ("admin".equals(username) && "123456".equals(password)) {
            SharedPrefUtils.putString(this, "USERNAME", username);
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("USER", new User(0,"admin", "管理员", "13845657895"));
            startActivity(intent);
            return;
        }

        if (dbHelper.validateUser(username, password)!=-1) {
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            SharedPrefUtils.putString(this, "USERNAME", username);
            // 获取用户信息并传递到主界面
            User user = dbHelper.getUserInfo(username);
            SharedPrefUtils.saveUserInfo(this, user.getId(), user.getUsername(), user.getRealName(), user.getPhone());
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("USER", user);

            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }
}